import {
	claimCompany,
	createCompany,
	deleteCompanyById,
	getCompanyById,
	getListByNameAndCusNo,
	getUnClaimCompanyForPage,
	queryCompanys,
	updateClaimStatus,
	updateCompany,
	getCompanyList
} from '../../services/company/company';
import {message} from "antd";
import Constants from '../../utils/Constants';

const R = require('ramda');

export default {
	namespace: 'company',
	state: {
		page: {},
		boolPage: {},
		companyList: {},
		dataSource: {},
		list: [],
		settlementUnitName: []	//结算单位
	},
	reducers: {
        /**
         * 刷新state
         * 
         * @param state 
         */
        refreshState(state, { payload }){
            return { ...state, ...payload };
        }
    },
	effects: {
        /**
         * 分页查询公司列表
         */
		*queryCompanys({ payload }, { call, put, select }) {
			let page = yield select(state => state.company.page);
			page = payload.page ? payload.page : page; //首次查询可以用默认的分页信息
			const res = yield call(queryCompanys, {
                company: payload.company,
				claimStatus: payload.claimStatus,
				dealt: payload.dealt,
				page: page
			});

			if (res && res.data.resultCode === "ok") {
				let content = res.data.content;
				let list = R.isNil(content.list) ? [] : content.list;
				yield put({
					type: 'refreshState',
					payload: {
						list: list,
						page: R.isNil(content.page) ? Constants.DEFAULT_PAGE : content.page //列表为空的时候重置state的分页信息
					}
				});
				if (payload.onSuccess) payload.onSuccess(list); //查询成功的回调函数
			} else {
				if (payload.onFail) payload.onFail(); //查询失败的回调函数
			}
		},

        /**
         * 根据id获取公司详情
         */
		*getCompanyById({ payload }, { call, put, select }) {
			if (payload.id) {
				const res = yield call(getCompanyById, { id: payload.id });

				if (res && res.data.resultCode === "ok") {
					let dataSource = R.isNil(res.data.content) ? {} : res.data.content;
					yield put({
						type: "refreshState",
						payload: {
							dataSource: R.isNil(res.data.content) ? {} : res.data.content
						}
					});
					if (payload.onSuccess) payload.onSuccess();
				} else {
					if (payload.onFail) payload.onFail();
				}
			} else {
				yield put({ type: "refreshState" });
				if (payload.onSuccess) payload.onSuccess();
			}
		},

        /**
         * 创建新的意向公司
         */
		*createCompany({ payload }, { call, select, put }) {
			let dataSource = R.clone(payload.dataSource);
			let productList = dataSource && dataSource.productList ? dataSource.productList : [];
			productList.map((product) => product.id && R.contains(Constants.TEMP_ID_PRE, product.id) ? product.id = null : product);
			const res = yield call(createCompany, { dataSource });

			if (res && res.data.resultCode === "ok") {
				message.info("意向公司新增成功！");
				if (payload.onSuccess()) payload.onSuccess();
			} else {
				if (payload.onFail) payload.onFail();

			}
		},

        /**
         *  删除公司
         */
		*deleteCompanyById({ payload }, { call, put, select }) {
			const res = yield call(deleteCompanyById, { id: payload.id });

			if (res && res.data.resultCode === "ok") {
				message.info("公司删除成功！");
				if (payload.onSuccess()) payload.onSuccess();
			} else {
				if (payload.onFail) payload.onFail();
			}
		},


        /**
         * 更新公司信息
         */
		*updateCompany({ payload }, { call, select, put }) {
			let productList = payload.dataSource && payload.dataSource.productList ? payload.dataSource.productList : [];
			productList.map((product) => R.contains(Constants.TEMP_ID_PRE, product.id) ? product.id = null : product);
			const res = yield call(updateCompany, { dataSource: payload.dataSource });

			if (res && res.data.resultCode === "ok") {
				message.info("公司信息更新成功");
				if (payload.onSuccess) payload.onSuccess();
			} else {
				if (payload.onFail) payload.onFail();
			}
		},

        /**
         *  公司认领
         */
		*claimCompany({ payload }, { call, put, select }) {
			const res = yield call(claimCompany, { id: payload.id });

			if (res && res.data.resultCode === "ok") {
				message.info("公司认领成功！");
				if (payload.onSuccess()) payload.onSuccess();
			} else {
				if (payload.onFail) payload.onFail();
			}
		},

		/**
         * 分页查待认领询客户
         * 
         */
        *getUnClaimCompanyForPage({ payload }, { call, put }) {
            const res = yield call(getUnClaimCompanyForPage, { ...R.omit(['onSuccess', 'onFail'])(payload) });
            if (res && res.data.resultCode === "ok") {
                yield put({
                    type: 'refreshState',
                    payload: {
                        list: res.data.content.list ? res.data.content.list : [],
                        boolPage: res.data.content.page ? res.data.content.page : Constants.DEFAULT_PAGE
                    }
                });
            } else {
                if (payload.onFail) payload.onFail();
            }
        },

		/**
         * 根据名称或编码查询客户
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *getListByNameAndCusNo({payload}, {call, put, select}) {
            const res = yield call(getListByNameAndCusNo, {nameOrCusNo: payload.nameOrCusNo});

            if (res && res.data.resultCode === "ok") {
                    // payload.onEmpty();
                yield put({
                    type: "refreshState",
                    payload: {
                        companyList: R.isNil(res.data.content) ? {} : res.data.content,
						settlementUnitName: Array.from(new Set(unitName))
                    }
				});
				let unitName = [];
                if(res.data.content){
                    res.data.content.map(item => { unitName.push(item.companyName); })        
                }
				if (payload.onSuccess) payload.onSuccess(res.data.content);
            } else {
                if( payload.onFail) payload.onFail()
            }
		},
		/**
         * 更新公司信息
         * 
         * @param call
         * @param put
         * @param select
         */
        *updateClaimStatus({ payload },{ call, put }){
            const res = yield call(updateClaimStatus, { ...R.omit(['onSuccess', 'onFail'])(payload) });
            if(res && res.data.resultCode === "ok"){
                message.info("退回成功！");
                if(payload.onSuccess) payload.onSuccess();
            } else {
                if(payload.onFail) payload.onFail();
            }
		},
		/**
         * 查询客户公司List
         *
         */
        *getCompanyList({ payload },{ call, put }){
            const res = yield call(getCompanyList, { ...R.omit(['onSuccess', 'onFail'])(payload) });
            if(res && res.data.resultCode === "ok"){
                yield put({
                    type: 'refreshState',
                    payload:{
                        companyList: R.isNil(res.data.content.list) ? [] : res.data.content.list
                    }
				});
				let unitName = [];
				if(res.data.content.list){
                    res.data.content.list.map(item => { unitName.push(item.companyName); })        
                }
                yield put({
                    type: 'refreshState',
                    payload: {
                        settlementUnitName: Array.from(new Set(unitName))
                    }
                })
            } else {
                if(payload.onFail) payload.onFail();
            }
        },
		/**
		 * 
		 * 
		 * 清空数据
		 */
		*cleanSource({}, { call, put }) {
			yield put({
				type: 'refreshState',
				payload: {
					dataSource: {}
				}
			});
		}
	},
	subscriptions: {
        setup({ history, dispatch }) {
            return history.listen(({ pathname }) => {
                const menus = JSON.parse(sessionStorage.getItem(Constants.USER_MENU));
                if(menus && !menus.find(item=>item.includes(pathname)) && pathname != '/logout'){
                    document.location.href = "/notAuthorized"
                }
            });
        }
    }
};